package com.yu.waterstation.app.common.interceptor;

import com.yu.waterstation.app.common.util.session.SessionUtil;
import com.yu.waterstation.common.common.annotation.NeedToken;
import com.yu.waterstation.common.common.annotation.VisitorAccess;
import com.yu.waterstation.common.common.constant.Const;
import com.yu.waterstation.common.common.enums.TokenType;
import com.yu.waterstation.common.common.exception.ServiceException;
import com.yu.waterstation.common.common.util.jwt.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * api拦截器
 */
@Slf4j
@Component
public class AppApiInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod))
            return super.preHandle(request, response, handler);

        NeedToken annotation = ((HandlerMethod) handler).getMethod().getAnnotation(NeedToken.class);
        if (annotation == null)
            return super.preHandle(request, response, handler);

        String token = SessionUtil.getToken(request);
        if (StringUtils.isEmpty(token) || !JWTUtil.verify(token))
            throw ServiceException.CONST_token_is_not_validate;

        // 检验登录
        Integer userId = JWTUtil.getUserId(token);
        if (annotation.value() == TokenType.ENUM_student_token) {
            if (userId == null || !SessionUtil.checkStudentLogin(userId))
                throw ServiceException.CONST_user_not_login;
            request.setAttribute(Const.CONST_student_id, userId);
        }
        if (annotation.value() == TokenType.ENUM_worker_token) {
            if (userId == null || !SessionUtil.checkWorkerLogin(userId))
                throw ServiceException.CONST_user_not_login;
            request.setAttribute(Const.CONST_worker_id, userId);
        }
        log.info("请求路径=[" + request.getServletPath() + "] 用户id=[" + userId + "]");

        // 游客模式
        if (userId != null && userId == 0 && !((HandlerMethod) handler).getMethod().isAnnotationPresent(VisitorAccess.class))
            throw ServiceException.CONST_visitor_mode_can_not_do_modify_operation;

        return super.preHandle(request, response, handler);
    }
}
